package com.snow.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.snow.utils.TaleUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:
 * 七牛云上传图片工具类
 * @author: snow
 * @Date: 2020-02-01
 **/
@Component
public class QiniuService {
    @Value("${qiniu.accesskey}")
    private String ACCESS_KEY;
    @Value("${qiniu.serectkey}")
    private String SECRET_KEY;
    @Value("${qiniu.bucket}")
    private String BUCKET;
    @Value("${qiniu.cdn.url}")
    public String URL;

    public String upload(MultipartFile file, String fileName){
        Configuration cfg = new com.qiniu.storage.Configuration(Zone.huadong());
        UploadManager uploadManager = new UploadManager(cfg);
        String key = null;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try{
            //上传文件
            Response response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);
            //解析结果
            DefaultPutRet ret = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("七牛云上传结果解析 key : " + ret.key);
            System.out.println("七牛云上传结果解析 hash : " + ret.hash);
            key = this.URL+ret.key;
        }catch (QiniuException qe){
            System.err.println(qe.response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }

    /**
     * 七牛云上传markdown文章中的本地图片
     * @param filePath
     * @return
     */
    public String uploadLocalFile(String filePath){
        String key = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            String filename = TaleUtils.getFileKey(filePath);
            Configuration cfg = new Configuration(Zone.huadong());
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String token = auth.uploadToken(BUCKET);
            Response response = uploadManager.put(fileInputStream, filename, token, null, null);
            DefaultPutRet ret = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("七牛云本地文件上传结果解析 key : " + ret.key);
            System.out.println("七牛云本地文件上传结果解析 hash : " + ret.hash);
            key = ret.key;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return key;
    }
}
